<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/10/10 0010
 * Time: 16:57
 */

namespace Cuke\Acl;

use Phalcon\Events\Event;
use Phalcon\Mvc\Dispatcher;

/**
 * ACL 调度器
 * @package Cuke\Acl
 * @property \Phalcon\Acl\Adapter\Memory $acl
 */
class AclDispatcher extends  \Phalcon\Di\Injectable
{

    public function beforeDispatch(Event $event, Dispatcher $dispatcher)
    {
        $role = $this->session->get('RoleCode');

        if(empty($role)){
            $role = 'Anonymous';
        }

        $controller = $dispatcher->getControllerName();
        $action = $dispatcher->getActionName();
        $params = $dispatcher->getParams();

        if (!$this->acl->isResource($controller)) {

            $dispatcher->forward([
                'controller' => 'Errors',
                'action'     => 'show404'
            ]);
            return false;
        }

        $allowed = $this->acl->isAllowed($role, $controller, $action,$params);

        if (!$allowed) {

            if($role === 'Anonymous'){

                header('Location:' . $this->url->get('account/login') . '?url=' . urlencode(base_uri($_SERVER['REQUEST_URI'])),true,302);
                return false;
            }

            $dispatcher->forward(array(
                'controller' => 'Errors',
                'action'     => 'show401'
            ));


            return false;
        }
        return true;
    }
}